<?php

namespace app\adminapi\controller\v2;

use app\adminapi\controller\AuthController;
use app\model\admin\QuestionModel;
use app\model\admin\QuestionTrainTypeModel;
use app\model\admin\TrainTypeModel;
use app\model\course\topic\Topic;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\exception\ValidateException;
use think\Request;

class Question extends AuthController
{
    public function list(Request $request)
    {
        $limit = input('size', 10);
        $page = input('page', 1);

        $where = [];
        $where[] = ['status', '=', 1];
        if ($title = $request->param('title', '')) {
            $where[] = ['title', 'like', '%' . $title . '%'];
        }
        if ($type = $request->param('type', '')) {
            $where[] = ['type', '=', $type];
        }
        $resource_type = input('resource_type', '');
        if ($resource_type) {
            $where[] = ['resource_type', '=', $resource_type];
        }
        $type_id = input('type_id', '');
        $company_id = $request->param('company_id', '');
        if ($company_id || $company_id === 0) {
            $where[] = ['company_id', '=', $company_id];
        }

        $data = QuestionModel::where($where)
            ->with('company')
            ->when($ids = input('ids', []), function ($query) use ($ids) {
                $query->whereIn('id', $ids);
            })
            ->when($exclude_ids = input('exclude_ids', []), function ($query) use ($exclude_ids) {
                $query->whereNotIn('id', $exclude_ids);
            })
            ->when($type_id, function ($query) use ($type_id) {
                $index = 0;
                foreach ($type_id as $typeID) {
                    if ($index == 0) {
                        $query->where('type_ids', 'like', "%,{$typeID},%");
                    } else {
                        $query->whereOr('type_ids', 'like', "%,{$typeID},%");
                    }
                    $index++;
                }
            })
            ->order('id desc')
            ->paginate($limit)
            ->each(function ($item) {
                $options = '';
                $options2 = [];
                if ($item['a']) {
                    $options .= 'A.' . $item['a'];
                    $options2[] = 'A.' . $item['a'];
                }
                if ($item['b']) {
                    $options .= ' B.' . $item['b'];
                    $options2[] = 'B.' . $item['b'];
                }
                if ($item['c']) {
                    $options .= ' C.' . $item['c'];
                    $options2[] = 'C.' . $item['c'];
                }
                if ($item['d']) {
                    $options .= ' D.' . $item['d'];
                    $options2[] = 'D.' . $item['d'];
                }
                if ($item['e']) {
                    $options .= ' E.' . $item['e'];
                    $options2[] = 'E.' . $item['e'];
                }
                if ($item['f']) {
                    $options .= ' F.' . $item['f'];
                    $options2[] = 'F.' . $item['f'];
                }
                $item['options'] = $options;
                $item['options2'] = $options2;
                if ($item['type_ids']) {
                    $typeIds = explode(',', $item['type_ids']);
                    $types = TrainTypeModel::whereIn('id', $typeIds)
                        ->column('title');
                    $item['type_name'] = implode(',', $types);
                } else {
                    $item['type_name'] = '';
                }

                if ($item['answer'] && is_array($item['answer'])) {
                    $item['answer'] = implode(',', $item['answer'] ?? []);
                }

                $item->company_name = $item['company']['company_name'] ?? '平台';
                return $item;
            });

        return app('json')->success([
            'list' => $data->items(),
            'total' => $data->total(),
        ]);
    }

    public function info(Request $request)
    {
        $trainTypes = DataType::getTrainType();
        $id = input('id', '');
        if ($id) {
            $data = QuestionModel::find($id);
            try {
                $data['selected_type_ids'] = DataType::getTrainTypeRelateIds($data['type_ids']);
                $data['type_ids'] = explode(',', trim($data['type_ids'], ','));
            } catch (\Exception $e) {
                $data['type_ids'] = [];
            }
        } else {
            $data = null;
        }

        return app('json')->success([
            'trainTypes' => $trainTypes,
            'data' => $data,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->only([
            'type_ids', 'type', 'title', 'a', 'b', 'c', 'd', 'e', 'f',
            'answer', 'desc'
        ]);
        $id = input('id', '');
        try {
            validate([
                'type_ids|培训类型' => 'require|array',
                'type|题目类型' => 'require|in:1,2,3',
                'title|题目内容' => 'require|max:255',
                'a|选项A' => 'max:255',
                'b|选项B' => 'max:255',
                'c|选项C' => 'max:255',
                'd|选项D' => 'max:255',
                'e|选项E' => 'max:255',
                'f|选项F' => 'max:255',
                'answer|题目答案' => 'require|array',
                'desc|题目解析' => 'max:65535',
            ])->check($data);
            $data['type_ids'] = ',' . implode(',', $data['type_ids']) . ',';
            $data['resource_type'] = 2;
            if (!$id) {
                $res = QuestionModel::create($data);
                $id = $res->id;
            } else {
                $res = QuestionModel::update($data, [
                    'id' => $id
                ]);
            }
        } catch (ValidateException $exception) {
            return app('json')->fail($exception->getMessage());
        }
        return app('json')->success();
    }

    public function delete(Request $request)
    {
        $id = input('id', '');
        $question = QuestionModel::where('status', 1)
            ->where('id', $id)
            ->find();
        if (!$id || !$question) {
            return app('json')->fail('未找到要删除的数据');
        }
        QuestionModel::update([
            'status' => -1,
        ], [
            'id' => $id
        ]);
        return app('json')->success();
    }

    public function uploadFile(Request $request)
    {
        $file = $request->file('file');
        $path = $file->getRealPath();
        $sht = IOFactory::load($path);
        $sheet = $sht->getSheet(0);
        $data = $sheet->toArray();
        $index = 0;
        $trainTypes = TrainTypeModel::where('status', 1)
            ->select();
        $trainTypes = array_column($trainTypes->toArray(), null, 'title');
        $insertData = [];
        foreach ($data as $k => $v) {
            $loop = [
                'title' => '', 'type' => '', 'a' => '', 'b' => '', 'c' => '', 'd' => '', 'e' => '', 'f' => '',
                'answer' => [], 'desc' => '', 'type_ids' => [],
            ];
            if ($index < 2) {
                $index++;
                continue;
            }
            $typeNames = explode(',', trim($v[0]));
            if (!$typeNames) {
                return app('json')->fail("第" . ($index + 1) . "行：请填写培训类型");
            }
            foreach ($typeNames as $name) {
                if (!isset($trainTypes[$name])) {
                    return app('json')->fail("第" . ($index + 1) . "行：培训类型\"" . $name . "\"不存在");
                } else {
                    $loop['type_ids'][] = $trainTypes[$name]['id'];
                }
            }
            if (!$v[1] || !in_array($v[1], ['单选题', '多选题', '判断题'])) {
                return app('json')->fail('第' . ($index + 1) . '行：题目类型请填写“单选体”、“多选题”、“判断题”中的一个');
            }
            $loop['type'] = ['' => 0, '单选题' => 1, '多选题' => 2, '判断题' => 3][$v[1]];
            if (!trim($v[2])) {
                return app('json')->fail('第' . ($index + 1) . '行：请填写题目内容');
            }
            $loop['title'] = trim($v[2]);
            $loop['a'] = trim($v[3]);
            $loop['b'] = trim($v[4]);
            $loop['c'] = trim($v[5]);
            $loop['d'] = trim($v[6]);
            $loop['e'] = trim($v[7]);
            $loop['f'] = trim($v[8]);
            if (!trim($v[9])) {
                return app('json')->fail('第' . ($index + 1) . '行：填写正确答案');
            } else {
                $answer = explode(',', trim($v[9]));
                if (!$answer) {
                    return app('json')->fail('第' . ($index + 1) . '行：正确答案格式错误，请填写A、B、C、D、E、F，多个答案用英文逗号隔开');
                }
                $answer = array_unique($answer);
                foreach ($answer as $vv) {
                    if (!in_array($vv, ['A', 'B', 'C', 'D', 'E', 'F'])) {
                        return app('json')->fail('第' . ($index + 1) . '行：正确答案格式错误，请填写A、B、C、D、E、F，多个答案用英文逗号隔开');
                    }
                }
            }
            $loop['answer'] = explode(',', trim($v[9]));
            $loop['desc'] = trim($v[10]);
            $loop['type_ids'] = ','.implode(',', $loop['type_ids']).',';
            $loop['create_time'] = time();
            $loop['resource_type'] = 2;
            $insertData[] = $loop;
            $index++;
        }
        if (count($insertData) < 1) {
            return app('json')->fail('没有可导入的数据');
        }
        (new Topic())->saveAll($insertData);
        return app('json')->success();
    }
}